package com.dyava.commons.clock;

import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * Created by jjliu on 2020/4/16.
 */
public abstract class ClockReceiver implements BeanFactoryAware{
    static Logger log = LoggerFactory.getLogger(ClockReceiver.class);

    BeanFactory beanFactory;

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        this.beanFactory = beanFactory;
    }

    public abstract void start();

    public void onReceiver(ClockMessage clockMessage){
        ClockHandle clockHandle = beanFactory.getBean(clockMessage.getHandleName(),ClockHandle.class);

        ParameterizedType ptype=null;
        Type[] types = clockHandle.getClass().getGenericInterfaces();
        for(Type t : types){
            ParameterizedType pt = (ParameterizedType)t;
            if(pt.getRawType().equals(ClockHandle.class)){
                ptype = pt;
                break;
            }
        }
        Type ftype = ptype.getActualTypeArguments()[0];
        Object t =JSON.parseObject(clockMessage.args,ftype);
        try {
            clockHandle.clock(t);
        }catch (Throwable e){
            log.error(e.getMessage());
        }
    }

}
